package com.github.kezhenxu94.playground.java.newfeatures.stream;

import org.junit.Before;
import org.junit.Test;

import java.io.File;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * Created by com.ikezhenxu.java.study on 4/11/15.
 */
public class StreamTest {

	private List<String>  strings;
	private List<Integer> integers;

	@Before
	public void init() {
		strings = Arrays.asList("a", "b", "ab", "abc", "abcd", "abcdef", "bcdefg");
		integers = Arrays.asList(1, 0, 2, 9, 3, 8, 7, 4, 5, 6, 12);
	}

	@Test
	public void testMaxBy() {

		// 两个最长的字符串, 结果是第一个
		final Optional<String> collect = strings.stream()
		                                        .collect(Collectors.maxBy(Comparator.comparing(String::length)));

		System.out.println(collect.get());
	}

	@Test
	public void testPartitioningBy() {
		final Map<Boolean, List<String>> collect = strings.stream()
		                                                  .collect(Collectors.partitioningBy(string -> string.length() > 3));
		System.out.println(collect.get(true));
		System.out.println(collect.get(false));

		final Map<Boolean, List<Integer>> collect1 = integers.stream()
		                                                     .collect(Collectors.partitioningBy(integer -> integer % 2 == 0));
		System.out.println("Even: " + collect1.get(true));
		System.out.println("Odd: " + collect1.get(false));
	}

	@Test
	public void testGroupingBy() {
		// 按第一个字母分组
		final Map<Character, List<String>> collect = strings.stream()
		                                                    .collect(Collectors.groupingBy(string -> string.charAt(0)));
		collect.forEach((character, strings) -> System.out.println("以 " + character + " 开头的" + strings));
	}

	@Test
	public void testJoining() {
		// 格式化输出字符串
		final String kk = integers.stream()
		                          .map(String::valueOf)
		                          .collect(Collectors.joining("->", "[", "]"));
		System.out.println(kk);
	}
	

	/**
	 * 1.使用 传递方法作为参数 （行为参数化） 列出当前目录下所有的目录
	 * 2.使用 Stream （序列处理（Sequence）这列目录。
	 * 3.使用 lambda 表达式将目录名为3个字符的输出
	 */
	@Test
	public void testStream () {
		File[] hiddenFileList = new File ("").listFiles ( File:: isDirectory );
		List<File> files = Arrays.asList ( hiddenFileList );
		files.stream ()
				.filter ( ( File file ) -> file.getName ().length () == 3 )
				.forEach ( ( File file ) -> System.out.println ( file.getName () ) );
	}

	@Test
	public void testLambda () {
		File[] hiddenFileList = new File ("").listFiles ( (File file ) -> file.isHidden () );
		System.out.println ( hiddenFileList.length );
	}
	
}
